"use strict";

const Controller = require("egg").Controller;

class ChatController extends Controller {
  async index() {
    const { app, socket, logger } = this.ctx;
    const nsp = app.io.of("/");

    // 监听消息事件
    socket.on("message", async (data) => {
      const { targetId, content } = data;
      const senderId = socket.id;

      // 保存消息到数据库
      await this.saveMessage(senderId, targetId, content);

      // 发送消息给目标用户
      if (nsp.sockets[targetId]) {
        nsp.sockets[targetId].emit("message", { senderId, content });
      }
    });

    // 处理断开连接
    socket.on("disconnect", () => {
      nsp.emit("offline", socket.id + " 下线了");
    });

    // 发送上线通知
    nsp.emit("online", socket.id + " 上线了");
  }

  async saveMessage(senderId, targetId, content) {
    const { app } = this.ctx;
    // await app.mysql.insert("messages", {
    //   sender_id: senderId,
    //   target_id: targetId,
    //   content,
    //   created_at: new Date(),
    // });
  }

  async getMessages(senderId, targetId) {
    const { app } = this.ctx;
    return await app.mysql.select("messages", {
      where: {
        sender_id: [senderId, targetId],
        target_id: [senderId, targetId],
      },
      orders: [["created_at", "asc"]],
    });
  }
}

module.exports = ChatController;
